package com.web4code.codegen.generator;

import java.io.File;
import java.util.List;
import java.util.Optional;

import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.CredentialsProvider;

import com.alibaba.fastjson.JSON;
import com.web4code.codegen.config.GenConfig;
import com.web4code.codegen.config.GenProjectTemplate;
import com.web4code.codegen.utils.GitUtils;
import com.web4code.codegen.utils.UrlUtils;

/**
 * 代码生成项目工具
 * 
 * @author web4code
 */
public class ProjectUtils {
    /**
     * 从指定模板初始化出新工程
     * @return
     */
    public static boolean initProjectFromTemplate(final String templateName, final String projectName) {
        List<GenProjectTemplate> templates = GenConfig.getGenConfig().getTemplates();
        if (templates == null) {
            System.out.println("no template config.");
            return false;
        }
        Optional<GenProjectTemplate> matchTemplate = templates.stream().filter(item -> templateName.equals(item.getTemplateName())).findAny();
        if (!matchTemplate.isPresent()) {
            System.out.println("no template match(" + templateName + ").");
            return false;
        }
        GenProjectTemplate template = matchTemplate.get();
        //
        downloadOrUpdateTemplate(template);
        System.out.println("complete "+template.getTemplateUrl());
        return true;
    }

    private static void downloadOrUpdateTemplate(final GenProjectTemplate template) {
        final String localTemplatePath = GenConfig.getGenConfig().getTemplatePath();
        final String gitName = UrlUtils.getNameFromGitUrl(template.getTemplateUrl());
        final String localTemplateStore = localTemplatePath + File.separator + gitName;
        System.out.println("localTemplateStore=" + localTemplateStore);
        // 获取credential
        CredentialsProvider credential = null;
        if (template.getGitUsername() != null) {
            credential = GitUtils.createCredential(template.getGitUsername(), template.getGitPassword());
        }
        // 先尝试升级本地模板
        try {
            Repository repo = GitUtils.getRepositoryFromDir(localTemplateStore);
            if (repo != null) {
                GitUtils.gitPull(repo, credential);
                return; // 升级完毕直接返回
            }
        } catch (Exception e) {
            // OK, continue
            e.printStackTrace();
        }
        // 其次从远端clone模板
        try {
            GitUtils.gitClone(template.getTemplateUrl(), localTemplateStore, null, credential);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return;
    }

    /**
     * 列出可用的项目模板列表
     * @return
     */
    public static boolean listProjectTemplates() {
        List<GenProjectTemplate> templates = GenConfig.getGenConfig().getTemplates();
        if (templates == null) {
            System.out.println("no template config.");
            return true;
        }
        for (final GenProjectTemplate template: templates) {
            System.out.println(JSON.toJSON(template));
        }
        return true;
    }
}
